// components/index-home/word-listening/index.js
const app = getApp();

Component({
  properties: {},
  
  data: {
    // UI状态
    isExpanded: false,
    isPlaying: false,
    
    // 单词数据
    learnedWords: [],
    learnedWordsCount: 0,
    currentWord: null,
    currentWordIndex: 0,
    totalWords: 0,
    
    // 播放控制
    playProgress: 0,
    playMode: 'sequence', // sequence: 顺序, random: 随机, loop: 单曲循环
    playModeIcon: 'r1.png',
    playModeText: '顺序播放',
    playSpeed: 1.0,
    autoPlayInterval: 3, // 自动播放间隔（秒）
    
    // 定时器
    playTimer: null,
    progressTimer: null
  },
  
  lifetimes: {
    attached() {
      this.loadLearnedWords();
    },
    
    detached() {
      this.cleanup();
    }
  },
  
  methods: {
    /**
     * 加载已学单词
     */
    loadLearnedWords() {
      try {
        const wordDataManager = app.getWordDataManager();
        const allWords = wordDataManager.getAllWords();
        
        // 筛选出已学习的单词（使用WordDataManager API）
        const learnedWords = Object.values(allWords).filter(word => {
          return wordDataManager.getWordLearnedStatus(word.id);
        });
        
        // 按最后学习时间排序（最近学习的在前）
        learnedWords.sort((a, b) => {
          const timeA = wordDataManager.getWordLastLearnTime(a.id) || '';
          const timeB = wordDataManager.getWordLastLearnTime(b.id) || '';
          return timeB.localeCompare(timeA);
        });
        
        this.setData({
          learnedWords: learnedWords,
          learnedWordsCount: learnedWords.length,
          totalWords: learnedWords.length,
          currentWord: learnedWords.length > 0 ? learnedWords[0] : null,
          currentWordIndex: 0
        });
        
        console.log('已加载已学单词:', learnedWords.length);
      } catch (error) {
        console.error('加载已学单词失败:', error);
        this.setData({
          learnedWords: [],
          learnedWordsCount: 0,
          totalWords: 0,
          currentWord: null
        });
      }
    },
    
    /**
     * 切换展开/折叠状态
     */
    toggleExpand() {
      const newExpandedState = !this.data.isExpanded;
      this.setData({
        isExpanded: newExpandedState
      });
      
      // 如果折叠时正在播放，继续播放
      // 如果展开时没有播放，不自动播放
    },
    
    /**
     * 切换播放/暂停
     */
    togglePlay() {
      if (!this.data.currentWord) {
        wx.showToast({
          title: '暂无可播放的单词',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      if (this.data.isPlaying) {
        this.pausePlay();
      } else {
        this.startPlay();
      }
    },
    
    /**
     * 开始播放
     */
    async startPlay() {
      if (!this.data.currentWord) return;
      
      this.setData({ isPlaying: true });
      
      // 播放当前单词
      await this.playCurrentWord();
      
      // 启动进度动画
      this.startProgressAnimation();
      
      // 设置自动播放下一个单词
      this.scheduleNextWord();
    },
    
    /**
     * 暂停播放
     */
    pausePlay() {
      this.setData({ isPlaying: false });
      
      // 停止音频
      const audioManager = app.getAudioManager();
      if (audioManager) {
        audioManager.stopPronunciation();
      }
      
      // 清除定时器
      this.clearTimers();
    },
    
    /**
     * 播放当前单词
     */
    async playCurrentWord() {
      let word = this.data.currentWord;
      if (!word) return;
      
      try {
        const audioManager = app.getAudioManager();
        const wordDataManager = app.getWordDataManager();
        
        // 检查单词是否已丰富，如果没有则先同步
        if (!wordDataManager._isWordEnriched(word)) {
          wx.showLoading({
            title: '正在同步单词数据...',
            mask: true
          });
          try {
            await wordDataManager.enrichWords([word.id], { forceRefresh: false });
            // 重新获取更新后的单词数据
            const updatedWord = wordDataManager.getWordById(word.id);
            if (updatedWord) {
              word = updatedWord; // 更新word引用
              this.setData({
                currentWord: updatedWord
              });
            }
          } finally {
            wx.hideLoading();
          }
        }
        
        // 获取发音设置
        const pronunciationType = wordDataManager.getPronunciationType();
        
        // 现在直接传入单词对象，让audioManager内部处理音频URL获取和错误处理
        await audioManager.playPronunciation(
          word,
          this.data.playSpeed,
          pronunciationType
        );
            
        // 等待音频播放完成
        await this.waitForAudioEnd(audioManager);
        
        // 等待一小段时间
        await this.sleep(500);
        
        // 播放中文释义
        if (word.chinese) {
          await audioManager.playTextToSpeech(word.chinese, this.data.playSpeed);
          await this.waitForAudioEnd(audioManager);
        }
        
      } catch (error) {
        console.error('播放单词失败:', error);
      }
    },
    
    /**
     * 等待音频播放结束
     */
    waitForAudioEnd(audioManager) {
      return new Promise((resolve) => {
        const checkInterval = setInterval(() => {
          const status = audioManager.getStatus();
          if (!status.isPlaying) {
            clearInterval(checkInterval);
            resolve();
          }
        }, 100);
        
        // 设置超时保护（最多等待10秒）
        setTimeout(() => {
          clearInterval(checkInterval);
          resolve();
        }, 10000);
      });
    },
    
    /**
     * 延迟函数
     */
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    
    /**
     * 启动进度动画
     */
    startProgressAnimation() {
      this.clearProgressTimer();
      
      const duration = this.data.autoPlayInterval * 1000;
      const startTime = Date.now();
      
      this.data.progressTimer = setInterval(() => {
        const elapsed = Date.now() - startTime;
        const progress = Math.min((elapsed / duration) * 100, 100);
        
        this.setData({ playProgress: progress });
        
        if (progress >= 100) {
          this.clearProgressTimer();
        }
      }, 50);
    },
    
    /**
     * 安排播放下一个单词
     */
    scheduleNextWord() {
      this.clearPlayTimer();
      
      this.data.playTimer = setTimeout(() => {
        if (this.data.isPlaying) {
          this.playNextWord();
        }
      }, this.data.autoPlayInterval * 1000);
    },
    
    /**
     * 播放下一个单词
     */
    async playNextWord() {
      const { currentWordIndex, totalWords, playMode, learnedWords } = this.data;
      
      if (totalWords === 0) return;
      
      let nextIndex;
      
      switch (playMode) {
        case 'sequence':
          nextIndex = (currentWordIndex + 1) % totalWords;
          break;
        case 'random':
          nextIndex = Math.floor(Math.random() * totalWords);
          break;
        case 'loop':
          nextIndex = currentWordIndex;
          break;
        default:
          nextIndex = (currentWordIndex + 1) % totalWords;
      }
      
      this.setData({
        currentWordIndex: nextIndex,
        currentWord: learnedWords[nextIndex],
        playProgress: 0
      });
      
      if (this.data.isPlaying) {
        await this.playCurrentWord();
        this.startProgressAnimation();
        this.scheduleNextWord();
      }
    },
    
    /**
     * 上一个单词
     */
    previousWord() {
      const { currentWordIndex, totalWords, learnedWords } = this.data;
      
      if (totalWords === 0) return;
      
      const prevIndex = (currentWordIndex - 1 + totalWords) % totalWords;
      
      this.setData({
        currentWordIndex: prevIndex,
        currentWord: learnedWords[prevIndex],
        playProgress: 0
      });
      
      // 如果正在播放，播放新单词
      if (this.data.isPlaying) {
        this.clearTimers();
        this.startPlay();
      }
    },
    
    /**
     * 下一个单词
     */
    nextWord() {
      const { currentWordIndex, totalWords, learnedWords } = this.data;
      
      if (totalWords === 0) return;
      
      const nextIndex = (currentWordIndex + 1) % totalWords;
      
      this.setData({
        currentWordIndex: nextIndex,
        currentWord: learnedWords[nextIndex],
        playProgress: 0
      });
      
      // 如果正在播放，播放新单词
      if (this.data.isPlaying) {
        this.clearTimers();
        this.startPlay();
      }
    },
    
    /**
     * 切换播放模式
     */
    togglePlayMode() {
      const modes = [
        { mode: 'sequence', icon: 'r1.png', text: '顺序播放' },
        { mode: 'random', icon: 'r2.png', text: '随机播放' }, 
        { mode: 'loop', icon: 'r3.png', text: '单曲循环' }
      ];
      
      const currentIndex = modes.findIndex(m => m.mode === this.data.playMode);
      const nextIndex = (currentIndex + 1) % modes.length;
      const nextMode = modes[nextIndex];
      
      this.setData({
        playMode: nextMode.mode,
        playModeIcon: nextMode.icon,
        playModeText: nextMode.text
      });
      
      wx.showToast({
        title: nextMode.text,
        icon: 'none',
        duration: 1500
      });
    },
    
    /**
     * 切换播放速度
     */
    toggleSpeed() {
      const speeds = [0.75, 1.0, 1.25, 1.5];
      const currentIndex = speeds.indexOf(this.data.playSpeed);
      const nextIndex = (currentIndex + 1) % speeds.length;
      const nextSpeed = speeds[nextIndex];
      
      this.setData({
        playSpeed: nextSpeed
      });
      
      wx.showToast({
        title: `播放速度: ${nextSpeed}x`,
        icon: 'none',
        duration: 1500
      });
    },
    
    /**
     * 切换自动播放间隔
     */
    toggleInterval() {
      const intervals = [2, 3, 5, 8];
      const currentIndex = intervals.indexOf(this.data.autoPlayInterval);
      const nextIndex = (currentIndex + 1) % intervals.length;
      const nextInterval = intervals[nextIndex];
      
      this.setData({
        autoPlayInterval: nextInterval
      });
      
      wx.showToast({
        title: `间隔: ${nextInterval}秒`,
        icon: 'none',
        duration: 1500
      });
      
      // 如果正在播放，重新安排下一个单词
      if (this.data.isPlaying) {
        this.clearPlayTimer();
        this.scheduleNextWord();
      }
    },
    
    /**
     * 清除播放定时器
     */
    clearPlayTimer() {
      if (this.data.playTimer) {
        clearTimeout(this.data.playTimer);
        this.data.playTimer = null;
      }
    },
    
    /**
     * 清除进度定时器
     */
    clearProgressTimer() {
      if (this.data.progressTimer) {
        clearInterval(this.data.progressTimer);
        this.data.progressTimer = null;
      }
    },
    
    /**
     * 清除所有定时器
     */
    clearTimers() {
      this.clearPlayTimer();
      this.clearProgressTimer();
    },
    
    /**
     * 清理资源
     */
    cleanup() {
      this.pausePlay();
      this.clearTimers();
    }
  }
});
